import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:star_author/utils/common_util/log_util.dart';
import 'package:video_player/video_player.dart';

enum StreamVideoPlayerType {
  list_list,
  index_page,
}

class StreamVideoPlayer extends StatefulWidget {
  String url;
  StreamVideoPlayerType type;
  double height;
  static String event = "stop_stream_video_player";

  StreamVideoPlayer({
    Key? key,
    this.url: "",
    this.type: StreamVideoPlayerType.list_list,
    this.height: 228,
  }) : super(key: key);

  @override
  State<StreamVideoPlayer> createState() => _StreamVideoPlayerState();
}

class _StreamVideoPlayerState extends State<StreamVideoPlayer> {
  VideoPlayerController? _videoPlayerController;

  bool isInitialize = false;

  @override
  void initState() {
    super.initState();
    this.height = widget.height.w;
    init();
  }

  init() async {
    _videoPlayerController = VideoPlayerController.network(
      widget.url,
      //有其他播放器播放的时候不会打断其他播放
      videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true),
    );
    _videoPlayerController?.initialize().then((value) async {
      await _videoPlayerController?.setVolume(0);
      await _videoPlayerController?.setLooping(true);
      await _videoPlayerController?.play();
      setState(() {
        isInitialize = true;
      });
    }).catchError((e) {
      LogUtil.v(('e:${e.toString()}'));
    });
  }

  @override
  void dispose() {
    // 移除生命周期监听
    super.dispose();
    _videoPlayerController?.removeListener(() {});
    _videoPlayerController?.dispose();
    LogUtil.v("销毁播放器");
  }

  double height = 228.w;

  @override
  Widget build(BuildContext context) {
    if (_videoPlayerController != null && !isInitialize) {
      return Container();
    }
    if (_videoPlayerController?.value.size.isEmpty ?? false) {
      return Container();
    }
    return buildWidget();
  }

  Widget buildWidget() {
    Map<StreamVideoPlayerType, Widget> map = {
      StreamVideoPlayerType.list_list: Container(
        alignment: Alignment.center,
        height: height,
        width: Get.width,
        child: OverflowBox(
          alignment: Alignment.center,
          maxHeight: _videoPlayerController?.value.size.height,
          maxWidth: _videoPlayerController?.value.size.width,
          child: FittedBox(
            fit: BoxFit.cover,
            child: SizedBox(
              width: _videoPlayerController?.value.size.width,
              height: _videoPlayerController?.value.size.height,
              child: VideoPlayer(_videoPlayerController!),
            ),
          ),
        ),
      ),
      StreamVideoPlayerType.index_page: VideoPlayer(_videoPlayerController!),
    };
    return map[widget.type] ?? Container();
  }
}
